package ejb;

import java.util.List;

import javax.annotation.Resource;
import javax.ejb.SessionContext;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import model.Citizen;
import utils.AbstractBean;
import dto.CitizenDTO;
import entitymanagers.CitizenManager;

@Stateless
public class CitizenManagerBean extends AbstractBean<Citizen> implements CitizenManager {
	
	@Resource
	private SessionContext context;
	@PersistenceContext
	private EntityManager em;
	
	public CitizenManagerBean() {
		super(Citizen.class);
	}

	@Override
	public void addCitizen(CitizenDTO citizenDTO) {
		Citizen citizen = new Citizen(citizenDTO);
		getEntityManager().persist(citizen);
		citizen = find(citizenDTO.getIdCitizen());
		em.persist(citizen);
	}

	@Override 
	public CitizenDTO[] getCitizens() {
		return convertToDTO(findAll());
	}

	@Override
	public CitizenDTO getCitizensByEmail(String email) {
		Citizen citizen = find(email);
		if (citizen == null){
			return new CitizenDTO();
		}
		return convertToDTO(citizen);
	}

	@Override
	public CitizenDTO getCitizensAlreadyVoted() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Citizen getPrincipalCitizen() {
		return find(getPrincipalEmail());
}
	
	public CitizenDTO getPrincipal(){
		try{
			return convertToDTO(find(context.getCallerPrincipal().getName()));
			
		}
		catch (Exception e){
			return null;
		}
	}
	public String getPrincipalEmail(){
		return context.getCallerPrincipal().getName();
	}
	@Override
	public void unregister() {
		remove(getPrincipalCitizen());
		
	}

	@Override
	public void update(CitizenDTO citizen) {
		em.merge(new Citizen(citizen));
		
	}

	@Override
	protected EntityManager getEntityManager() {
		return em;
	}
	private static CitizenDTO convertToDTO(Citizen citizen){
		CitizenDTO citizenDTO = new CitizenDTO();
		citizenDTO.setEmail(citizen.getEmail());
		citizenDTO.setName(citizen.getName());
		citizenDTO.setSurname(citizen.getSurname());
		citizenDTO.setDateBirth(citizen.getDateBirth());
		return citizenDTO;
	}
	public static CitizenDTO[] convertToDTO(List<Citizen> citizens){
		CitizenDTO[] arrCitizens = new CitizenDTO[citizens.size()];
		int i = 0;
		for (Citizen c : citizens){
			arrCitizens[i++] = convertToDTO(c);
		}
		return arrCitizens;
	}

	@Override
	public CitizenDTO getCitizen() {
		CitizenDTO citizenDTO = convertToDTO(getPrincipalCitizen());
		return citizenDTO;
	}

	
}
